// CustomerServiceWebSocketServer.java
package org.example.websocket;

import com.alibaba.fastjson.JSON;
import org.example.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/customer-service")
@Component
public class CustomerServiceWebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceWebSocketServer.class);
    
    // 存储客服的WebSocket会话
    private static final Map<String, Session> CUSTOMER_SERVICE_SESSIONS = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session) {
        logger.info("客服WebSocket连接建立: {}", session.getId());
        CUSTOMER_SERVICE_SESSIONS.put(session.getId(), session);
    }
    
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("收到客服消息: {}", message);
        
        // 转发消息给用户
        // 这里需要根据消息中的toId找到对应的用户会话
        try {
            ChatMessage chatMessage = JSON.parseObject(message, ChatMessage.class);
            if (chatMessage.getToId() != null) {
                // 发送给指定用户
                UserChatWebSocketServer.sendToUser(chatMessage.getToId(), message);
            }
        } catch (Exception e) {
            logger.error("处理客服消息失败", e);
        }
    }
    
    @OnClose
    public void onClose(Session session) {
        logger.info("客服WebSocket连接关闭: {}", session.getId());
        CUSTOMER_SERVICE_SESSIONS.remove(session.getId());
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("客服WebSocket错误: {}", error.getMessage());
    }
    
    // 广播消息给所有客服
    public static void broadcastToCustomerService(String message) {
        logger.info("准备广播消息给所有客服: {}", message);
        logger.info("当前在线客服数量: {}", CUSTOMER_SERVICE_SESSIONS.size());
        //@TODO
//      这部分代码后续需要修改,要把消息发送到客户比较少的客服那里
        CUSTOMER_SERVICE_SESSIONS.values().forEach(session -> {
            try {
                session.getBasicRemote().sendText(message);
                logger.info("成功发送消息给客服 {}", session.getId());
            } catch (IOException e) {
                logger.error("广播消息失败, sessionId: {}, error: {}", session.getId(), e.getMessage());
            }
        });
    }
}